<template>
  <a-modal 
    :visible="visible"
    okText="提交" 
    cancelText="关闭"
    :title="title"
    :destroyOnClose="true"
    :maskClosable="false"
    :keyboard="false"
    width="800px"
    @cancel="closeModal()" 
    :confirmLoading="confirmLoading"
    @ok="handleSubmit">
    <a-form :form="form"  :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
      
      <a-form-item label="账户类型">
        <a-radio-group 
          :options="typeOptions"
          @change="e=> accountType = e.target.value"
          v-decorator="[
            'accountType',
            { initialValue: accountType,rules: [{ required: true, message: '请选择账户类型' }] }
          ]"
        />
      </a-form-item>
      <a-form-item label="账户名称">
        <a-input
          :max-length="30"
          v-decorator="['accountName', { rules: [{ required: true, message: '请填写账户名称' }] }]"
          placeholder="请填写账户名称"
        />
      </a-form-item>
      <a-form-item label="银行卡号">
        <a-input
          :max-length="19"
          v-decorator="['cardNumber', { rules: [{ required: true, message: '请填写银行卡号' },{ pattern: /^\d{16,19}$/, message: '请填写正确的银行卡号' }] }]"
          placeholder="请填写银行卡号"
        />
      </a-form-item>
      <a-form-item label="开户银行">
        <a-select 
          allowClear
          :options="openAccountBankOptions"
          placeholder="请选择开户银行"
          v-decorator="[
            'openAccountBank',
            { rules: [{ required: true, message: '请选择开户银行' }] }
          ]"
        />
      </a-form-item>

      <a-row v-if="accountType == 2">
        <a-form-item label="开户地区" :help="addressHelp">
          <a-cascader :field-names="{ label: 'areaName', value: 'id', children: 'children' }"
                      :options="areaTree"
                      :show-search="true"
                      :changeOnSelect="true"
                      placeholder="请选择开户地区"
                      v-decorator="[
                  'treepath',
                { rules: [{ required: true, message: '请选择开户地区' }] }
                ]" />
        </a-form-item>
        <a-form-item label="支行名称">
          <a-input
            :maxLength="30"
            v-decorator="['subBank', {  }]"
            placeholder="请输入支行名称"
          />
        </a-form-item>
      </a-row>



      <a-form-item label="银行预留手机号">
        <a-input
          :maxLength="11"
          v-decorator="['phone', { rules: [
            { required: true, message: '请填写银行预留手机号' },
            {pattern: /^1[3,4,5,6,7,8,9]\d{9}$/, message: '请填写正确的手机号'}
          ] }]"
          placeholder="请填写银行预留手机号"
        />
      </a-form-item>
    </a-form>
    <!-- 校验预留手机号弹窗 -->
    <check-reserved-phone v-if="values" :visible="checkReservedVisible" :values="values" @cancel="closeCheckReservedModal"/>
  </a-modal>
</template>
<script>
import {getAreaTree} from '@/utils/asyncUtils'
import {treeFindPath} from '@/utils'
import CheckReservedPhone from './CheckReservedPhone'
import isEmpty from 'lodash/isEmpty'
export default {
  name: 'card-info',
  components: {
    CheckReservedPhone
  },
  props: {
    record: {
      type: Object,
      default() {
        return {}
      }
    },
    visible: {
      type: Boolean,
      default: false
    },
  },
  computed: {
    title () {
      return this.record && this.record.id ? '修改银行卡' : '添加银行卡'
    },
    
  },
  data () {
    return {
      addressHelp: '正在获取地区信息，请稍等...',
      form: this.$form.createForm(this, { name: 'coordinated', onValuesChange: this.onValuesChange }),
      areaTree: [],
      confirmLoading: false,
      checkReservedVisible: false,
      openAccountBankOptions: [
        {label: '农业银行', value: 1}
      ],
      accountType: 1,
      typeOptions: [
        {label: '对私银行账户', value: 1},
        {label: '对公银行账户', value: 2},
      ],
      values: null
    }
  },
  watch: {
    visible (value) {
      this.accountType = 1
      this.confirmLoading = false
      this.checkReservedVisible = false
      this.values = null
      if (value) {
        if (!(this.areaTree && this.areaTree.length)) {
          this.addressHelp = '正在获取地区信息，请稍等...'
          getAreaTree().then((res) => {
            this.areaTree = res;
            this.addressHelp = ''
          });
        }
        if (this.record && this.record.id) {
          this.getCardInfo()
        }
      }
    }
  },
  methods: {
    // 当表单值发生变化
    onValuesChange (props, values) {
      if (isEmpty(values)) return
      const result = {}
      Object.keys(values).forEach(key => {
        switch (key) {
          case 'cardNumber':
          case 'phone':
            const number = values[key].replace(/\D/g,'')
            if (number !== values[key]) {
              result[key] = number
            }
            break;
        
          default:
            break;
        }
      })
      if (!isEmpty(result)) {
        this.$nextTick(()=> {
          this.form.setFieldsValue(result)
        })
      }
    },
    getCardInfo() {
      this.$get('/bank/card/id', {id: this.record.id}).then(res => {
        if (res && res.returnCode === 1000) {
          const record = res.dataInfo
          this.accountType = record.accountType
          if (record.accountType == 2 && record.treepath) {
            record.treepath = record.treepath.split(',')
            record.treepath.splice(0,1)
          }
          this.$nextTick(()=> {
            const formItems = this.form.getFieldsValue();
            Object.keys(formItems).forEach(key => {
              formItems[key] = record[key]
            })
            this.form.setFieldsValue(formItems);
          })
        }
      })

    },
    // 点击提交
    handleSubmit () {
      this.values = null
      this.confirmLoading = true
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = false
          this.values = values
          this.checkReservedVisible = true
        } else {
          this.confirmLoading = false
        }
      });
    },
    // 发请求添加银行卡
    addBankRequest (smsParams) {
      const values = this.values
      let url = '/bank/card/add'
      if (this.record && this.record.id) {
        url = '/bank/card/update'
        values.id = this.record.id
      }
      if (values.accountType == 2) {
        const lastId = values.treepath[values.treepath.length - 1]
        values.region = treeFindPath(this.areaTree, data=>lastId == data.id, [],'areaName').join('')
        values.treepath = `0,${values.treepath.join(',')}`
      }
      this.$post(url, {...values, ...smsParams}).then(res => {
        this.confirmLoading = false
        if (res && res.returnCode === 1000) {
          this.$message.success('保存成功！')
          this.closeModal(true)
        }
      }).catch(err=> {
        this.confirmLoading = false
      })
    },
    // 关闭添加弹窗
    closeModal (freshList) {
      this.form.resetFields()
      this.$emit('cancel', freshList)
    },
    // 关闭校验预留手机号弹窗
    closeCheckReservedModal (smsParams) {
      this.checkReservedVisible = false
      if (smsParams) { // 预留手机号验证成功
        this.addBankRequest(smsParams)
      }
    }
  }
}
</script>